<template>
  <div class="flex-d-col h-100%">
    <breadcrumb />
    <div class="app-main-container h-100% flex">
      <div class="left flex-d-col">
        <div class="title">规章目录</div>
        <organizeQuestionBanks
          :treeFilterInput="false"
          @ac-tree-data="
            (val, arr) => {
              leftData = arr;
              getTreeData(val);
            }
          "
        ></organizeQuestionBanks>
      </div>
      <div class="right flex-d-col flex-1 ml-20px">
        <div class="title">规章列表</div>
        <div class="flex-d-col h-100%">
          <div class="search">
            <el-form :inline="true" :model="formSearch" size="small">
              <el-form-item>
                <el-input
                  v-model="formSearch.name"
                  class="w-200px"
                  placeholder="输入搜索关键词"
                  clearable
                  @change="searchChange"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="formSearch.isActive"
                  placeholder="选择状态"
                  class="w-100px!"
                  clearable
                  @change="searchChange"
                >
                  <el-option
                    v-for="item in [
                      { value: true, label: '启用' },
                      { value: false, label: '停用' },
                    ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <!-- <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)"
                  >搜索</el-button
                >
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
              </el-form-item> -->
            </el-form>
          </div>
          <div class="search-con">
            <div class="flex-x-between">
              <div></div>
              <div class="btn">
                <el-button type="primary" size="small" @click="addEdit('add')"
                  >添加</el-button
                >
              </div>
            </div>
            <el-table :data="tableData.data" style="width: 100%" fit>
              <el-table-column prop="name" label="规章名称" />
              <el-table-column prop="publishTime" label="最新发布时间" />
              <el-table-column prop="enabled" label="版本状态">
                <template #default="scope">
                  <el-text :type="scope.row.enabled ? 'success' : 'info'">{{
                    scope.row.enabled ? "启用" : "停用"
                  }}</el-text>
                </template>
              </el-table-column>
              <el-table-column prop="versionCount" label="版本数量" />
              <el-table-column prop="lastModificationTime" label="更新时间" />
              <el-table-column prop="address" label="操作" width="250">
                <template #default="scope">
                  <el-button type="primary" size="small" link @click="goView(scope.row)"
                    >查看</el-button
                  >
                  <el-button
                    type="primary"
                    size="small"
                    link
                    @click="addEdit('rename', scope.row)"
                    >重命名</el-button
                  >
                  <el-button
                    v-if="scope.row.isActive"
                    type="primary"
                    size="small"
                    link
                    @click="publishNew(scope.row)"
                    >发布新版</el-button
                  >
                  <!-- <el-popconfirm title="确定要删除？" @confirm="del(scope.row)">
                    <template #reference>
                      <el-button type="danger" size="small" link>删除</el-button>
                    </template>
                  </el-popconfirm> -->
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              class="flex-x-center mt-10px"
              small
              background
              layout="prev, pager, next"
              v-model:current-page="page.index"
              :page-size="page.size"
              :total="page.total"
              hide-on-single-page
              @current-change="pageChange"
            />
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="addEditVisible.show"
      :title="addEditVisible.title"
      width="600"
      @close="addEditClose"
    >
      <el-form
        :key="addEditVisible.show"
        ref="RefForm"
        :model="addEditVisible.data"
        label-width="120"
        class="w-100%"
        :rules="rules"
      >
        <el-form-item
          v-if="addEditVisible.type != 'rename'"
          label="上传规章文件"
          prop="fileId"
        >
          <el-upload
            ref="upload"
            action="/api/api/FileManage/CreateUploadFile"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="1"
            name="patrolFileInfo"
            class="w-200px"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传
            </el-button>
          </el-upload>
          <el-input class="hidden" v-model="addEditVisible.data.fileId"></el-input>
        </el-form-item>
        <el-form-item label="规章名称" prop="name">
          <el-input
            type="textarea"
            v-model="addEditVisible.data.name"
            class="w-400px"
            placeholder=""
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="addEditVisible.type != 'rename'"
          label="发布日期"
          prop="publishTime"
        >
          <el-date-picker
            v-model="addEditVisible.data.publishTime"
            type="date"
            class="w-200px!"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addEditClose">取消</el-button>
          <el-button type="primary" @click="addEditSave" :loading="loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--  -->
    <newVersion
      v-if="newVersionData.show"
      :show="newVersionData.show"
      :data="newVersionData.data"
      @close="
        (val, reload) => {
          newVersionData.show = false;
          reload ? searchChange() : '';
        }
      "
    ></newVersion>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Regulations",
  inheritAttrs: false,
});
import { useRoute, useRouter } from "vue-router";
import { ApiUploadFile } from "@/api/file";
import {
  ApiPostRegulation,
  ApiGetRegulation,
  ApiPutRegulationId,
  ApiDelRegulationId,
} from "@/api/resource-management/regulations";
import { Search } from "@element-plus/icons-vue";
import organizeQuestionBanks from "@/components/organizeQuestionBanks/index.vue";
import type {
  UploadRawFile,
  UploadRequestOptions,
  UploadUserFile,
  UploadFile,
  UploadProps,
  UploadInstance,
  FormInstance,
  FormRules,
} from "element-plus";
import { genFileId, dayjs } from "element-plus";
import newVersion from "./components/newVersion.vue";

const route = useRoute();
const router = useRouter();
const loading = ref(false);

const { params, query } = route;
const { path } = params;

let leftData = {};

const formSearch = ref({});
const searchChange = () => {
  if (addEditVisible.data.id) {
    getTreeData({ id: addEditVisible.data.id });
  }
};
onActivated(() => {
  searchChange();
});

const addEditVisible = reactive({
  type: "add",
  show: false,
  title: "添加规章",
  data: {},
});
const RefForm = ref(null);
const rules = reactive({
  fileId: [{ required: true, message: "规章文件必填", trigger: "change" }],
  name: [{ required: true, message: "规章名称必填", trigger: "change" }],
  publishTime: [{ required: true, message: "发布日期必填", trigger: "change" }],
});
// 添加规章
const addEdit = (type, data) => {
  addEditVisible.type = type;
  if (type == "add") {
    addEditVisible.title = "添加规章";
  } else if (type == "rename") {
    addEditVisible.data = JSON.parse(JSON.stringify(data));
    addEditVisible.title = "规章重命名";
  }
  addEditVisible.show = true;
};
// 删除
const del = (data) => {
  ApiDelRegulationId(data).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: "删除成功！",
        type: "success",
      });
      // if(data.id == formData.value.oId) {}
      searchChange();
    }
  });
};

// 上传成功
const handleSuccess = (res) => {
  if (res.code == 200) {
    addEditVisible.data.name =
      addEditVisible.data.name || res.data.fileName.replace(/\.[^/.]+$/, "");
    addEditVisible.data.regulationFileId = res.data.id;
  }
};
const addEditSave = () => {
  const visibleType = {
    add: ApiPostRegulation,
    edit: "",
    rename: ApiPutRegulationId,
  };
  RefForm.value.validate((valid, fields) => {
    // if (valid) {
    loading.value = true;
    visibleType[addEditVisible.type]({
      railwayBureau: null,
      trainDepotName: null,
      stationName: null,
      enabled: true,
      upDateTime: addEditVisible.data.publishTime,
      updatePerson: "00000000-0000-0000-0000-000000000000",
      ...addEditVisible.data,
      ...leftData,
    })
      .then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: `${addEditVisible.type == "add" ? "新增" : "修改"}成功`,
            type: "success",
          });
          addEditClose();
          debugger;
          getTreeData({ id: addEditVisible.data.id });
        }
      })
      .finally(() => {
        loading.value = false;
      });
    // }
  });
};
const upload = ref<UploadInstance>();
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  upload.value!.submit();
};
const handleRemove = () => {
  addEditVisible.data.fileId = "";
};
const addEditClose = () => {
  let orgId = addEditVisible.data.id;
  addEditVisible.data = {};
  addEditVisible.data.id = orgId;
  addEditVisible.show = false;
};
// setTimeout(() => {
//   console.log(import.meta.env.VITE_APP_BASE_API);
// }, 1000);

// 分页
const page = reactive({
  index: 1,
  size: 10,
  total: 0,
});
const pageChange = (val) => {
  page.index = val;
  getTreeData({ id: addEditVisible.data.id });
};

const getTreeData = (val) => {
  // addEditVisible.data.addEditVisible.data.id = val?.id;
  if (val?.id) {
    let params = {
      railwayBureau: null,
      trainDepotName: null,
      stationName: null,
      keyWord: "",
      // enable: null,
      pageIndex: page.index,
      pageSize: page.size,
      ...leftData,
    };
    ApiGetRegulation(params).then((res) => {
      if (res.code == 200) {
        tableData.data = res.data.data.map((e) => {
          return {
            ...e,
            publishTime: e.publishTime && dayjs(e.publishTime).format("YYYY-MM-DD"),
            lastModificationTime:
              e.lastModificationTime &&
              dayjs(e.lastModificationTime).format("YYYY-MM-DD"),
          };
        });
        page.total = res.data.dataCount;
      }
    });
  }
};
// 规章列表
const tableData = reactive({
  data: [],
  totalCount: 0,
});

const newVersionData = reactive({
  show: false,
  data: {},
});
const publishNew = (data) => {
  newVersionData.data = JSON.parse(JSON.stringify(data));
  newVersionData.show = true;
};

const goView = (data) => {
  router.push({
    path: `${route.path}/detail`,
    query: { id: data.id },
  });
};
</script>

<style scope lang="scss">
.app-main-container {
  .title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: bold;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.9);
    line-height: 21px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    margin-bottom: 20px;
  }
  .left {
    height: 100%;
  }
  .right {
    & > .flex-d-col {
      background: linear-gradient(180deg, #ffffff 0%, rgba(255, 255, 255, 0.8) 100%);
      border-radius: 20px 20px 20px 20px;
      border: 1px solid rgba(4, 42, 94, 0.1);
      padding: 20px;
    }
    .el-input {
      &-group__append,
      &-group__prepend {
        padding: 0 10px;
      }
    }
    .con {
      border: 1px solid rgba(0, 57, 137, 0.1);
      border-radius: 20px 20px 0px 0px;
      padding: 10px 20px 20px;
      .el-checkbox-group {
        font-size: 14px;
        line-height: inherit;
      }
      .list {
        .title {
          margin-bottom: 10px;
        }
        .type {
          background-color: #1759b5;
          font-size: 12px;
          padding: 4px 8px;
          border-radius: 6px;
          color: #fff;
        }
        .answer {
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6);
          pointer-events: none;
        }
        .source {
          border: 1px solid rgba(0, 0, 0, 0.1);
          padding: 8px;
          border-radius: 10px;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6);
        }
      }
    }
  }
}
</style>
